package vue;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import metier.DefaultHttpClientPerso;
import modele.SimpleService;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.finalprojet.R;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;


@SuppressLint("HandlerLeak")
public class DashBoard extends Activity {


	Intent Simpleservice;
	public int erreur=0;
	public Bitmap[] bmp;
	public Dialog dialog;
	public String pseudo = null;
	public String id;
	Messenger mService = null;
	ListView notif = null;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            pseudo = getIntent().getStringExtra("pseudo");
           
            Simpleservice = new Intent(DashBoard.this, SimpleService.class);
            Simpleservice.putExtra("pseudo", pseudo);
	    	
			startService(Simpleservice);
            setContentView(R.layout.activity_dash_board);
            
            id = getIntent().getStringExtra("id");
            notif = (ListView)findViewById(R.id.listnotification);

            httpTasks pok = new httpTasks();
            pok.execute(pseudo);
	       
      
            
	    	
            bindService(Simpleservice, mConnection,BIND_AUTO_CREATE);
            
            final Button forum = (Button)findViewById(R.id.oki);
            forum.setOnClickListener(new OnClickListener() 
            {
        		
        		public void onClick(View v) 
        		
        			{
        			Intent nextScreen = new  Intent (getApplicationContext (), Forum.class );
        			
    				startActivity (nextScreen);

        	        
        			}
        	});
            
            
            final ImageView Reglage = (ImageView)findViewById(R.id.reglage);
            Reglage.setOnClickListener(new OnClickListener() 
            {
        		
        		public void onClick(View v) 
        		
        			{
        			Intent nextScreen = new  Intent (getApplicationContext (), Reglage.class );
        			nextScreen.putExtra("pseudo", pseudo);
        			nextScreen.putExtra("id", id);
    				startActivity (nextScreen);

        	        
        			}
        	});
            
            
            
            Button logout =(Button)findViewById(R.id.logout);
            
            logout.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					startActivity (new  Intent (getApplicationContext (), EcranAccueil.class ));

					
				}
			});
            
            
            ImageView jeuEchec =(ImageView)findViewById(R.id.JeuxEchec);
            jeuEchec.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					Intent jeuEchec = new  Intent (getApplicationContext (), JeuEchec.class );  
					jeuEchec.putExtra("pseudo", pseudo);
					startActivity (jeuEchec);

					
				}
			});
            
            

            

     
        }
        
        
    	final Messenger mMessenger = new Messenger(new IncomingHandler());
    	
    	
    	
    	class IncomingHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
            	Log.e("HANDLER", "DASHBOARD");
                switch (msg.what) {
               
                case SimpleService.MSG_MAJ_LIST:
                	
                	notif.setAdapter(new ArrayAdapter<String>(DashBoard.this, android.R.layout.simple_list_item_1,msg.getData().getStringArrayList("online")));
                	
                  
                    break;
                    
                case SimpleService.NOTIF_JEU:
                	showDialogGame(msg.getData().get("str1"));
                	
                case SimpleService.NOTIF_NEWCHAT:
                	notifierNewChat(msg.getData().get("str1"));
                   
            default:break;
                  
                }
            
        }

			private void notifierNewChat(Object object) {
			
				String[] tab = ((String)object).split("%");
				//ListAdapter adapter= ((ListAdapter)notif.getAdapter());
				
				List<HashMap<String, String>> liste = new ArrayList<HashMap<String, String>>();

				HashMap<String, String> element = new HashMap<String, String>();
				element.put("numero", tab[0]);
				element.put("pseudo", tab[1] + " desirerai parler avec vous");
				liste.add(element);
				
				
				ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
						liste, android.R.layout.simple_list_item_2,new String[]{"pseudo"}, new int[] {android.R.id.text1});
					    notif.setAdapter(adapter);
					   notif.setOnItemClickListener(new OnItemClickListener() 
					   {

						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							
							Intent nextScreen = new  Intent (getApplicationContext (), ChatBox.class );
		        			
								nextScreen.putExtra("id", id);
								
								HashMap<String, String> element = (HashMap<String, String>)notif.getItemAtPosition(arg2);
								element.get("pseudo");
								
								
								
								nextScreen.putExtra("pseudo", element.get("pseudo"));
								nextScreen.putExtra("numroom", element.get("no"));
								nextScreen.putExtra("pseudomoi", pseudo);
							
		    				startActivity (nextScreen);
						
		                	
		                    
						}	
						
					});
				
				
				
			}
    	}
  	  private ServiceConnection mConnection = new ServiceConnection() {


  			public void onServiceConnected(ComponentName arg0, IBinder arg1) {

  	            mService = new Messenger(arg1);
  	           
  	            try {
  	                Message msg = Message.obtain(null, SimpleService.MSG_REGISTER_CLIENT);
  	                msg.replyTo = mMessenger;
  	                mService.send(msg);
  	            } catch (RemoteException e) {
  	            }
  				
  			}

  			public void onServiceDisconnected(ComponentName name) {  				
  			}
  	    };
        

        protected void onRestart() {
        	 super.onRestart();
        	 Log.e("onrestart","onrestart");
        	  httpTasks poki = new httpTasks();
              poki.execute(pseudo);
           
            
              
              
              
        }
       
    	
        
        public void showDialogGame(Object object) {
        	final String[] tab = ((String)object).split("%");
        	
        	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DashBoard.this);
			alertDialogBuilder.setTitle("Demande de jeu")
				.setMessage("jouer au "+ tab[0] + " avec " + tab[1] +" ?")
				.setCancelable(false)
				.setPositiveButton("Jouer",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
					
        				 Message msg = Message.obtain(null, SimpleService.NOTIF_JEU);
	     	                msg.replyTo = mMessenger;
	     	                
	     	               
	     	               Bundle b = new Bundle();
	     	            
								b.putString("str1","jeu%++%"+tab[1]);
							
	     	                msg.setData(b);
	     	                try {
								mService.send(msg);
							} catch (RemoteException e1) {
								e1.printStackTrace();
							}

        				//startActivity (nextScreen);
					}
				  });
			alertDialogBuilder
			.setNegativeButton("Ne pas jouer",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
					
				}
			  });

				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			
		}



		public class httpTasks extends AsyncTask< String, Void, Object[]>   
        {


        	 protected Object[] doInBackground(String... arg0) {
        		 
        		Log.e("httptask","go");
        		
        		
        		 String tabstring = null;
        	
     	       DefaultHttpClientPerso httpclient = new DefaultHttpClientPerso();
        		
        		HttpGet httpget = new HttpGet(EcranAccueil.URLSERVEUR+"/android/checkOnline.php?id="+pseudo);
       
        			HttpResponse response = null;
        			 JSONArray main =null;
        		
        			Bitmap[] bmp = null;
        			
        			 try
        			 {
        				 
        				 response = httpclient.execute(httpget);
                         tabstring =  EntityUtils.toString(response.getEntity());
                         
                         try {
                        	 main = new JSONArray(tabstring); 
						} catch (Exception e) {
							erreur=1;
							Log.e("erreur", e.getMessage());
						}
                    	
                    	
                         
                     if ( erreur ==0)  
                     {
                    	bmp = new Bitmap[main.length()];
                    	
                    	
                    	
                    	
                    	for    ( int i = 0 ; i< main.length() ; i++ )
                    	{
                    		
                    		
                    		JSONObject ok = main.getJSONObject(i);
                    		String url = EcranAccueil.URLSERVEUR + "/android/upload/smallimg/";
                             url+=ok.get("id").toString()+".jpg";         
                    		 URLConnection conn = new URL(url).openConnection();
                    		  String userpassword = "projet.echec" + ":" + "eepuhohx";
                    	      String encodedAuthorization =  Base64.encodeToString( userpassword.getBytes(), Base64.NO_WRAP );
                    	      conn.setRequestProperty("Authorization", "Basic "+
                    	            encodedAuthorization);
                    		
        	    	      	conn.connect();
        	    	      	
        	    	      	 InputStream is = conn.getInputStream();
        	    	       
        	    	      	 BufferedInputStream bis = new BufferedInputStream(is, 100000);
        	    	       
        	    	      	 Bitmap bm = BitmapFactory.decodeStream(bis);
        	    	      	bis.close();
        	    	      	is.close();

        	    	      	bm.getScaledHeight(40);
        	    	      	bm.getScaledWidth(40);
							bmp[i] = bm;
							

                    	}  

                     }

        		} catch (Exception e)
        		{
        			e.printStackTrace();
        		}

        			 Object[] ret = new Object[2];
        			 ret[0] = tabstring;
        			 ret[1] = bmp;

        			 return ret;
        	 }

        	 
        	 
        	 
        	 
        	 
        	 
        		protected void onPostExecute(Object[] obj) 
        		{
        				
        			bmp = (Bitmap[])obj[1];
        			String response = (String)obj[0];
        			
        			ListView maListViewPerso;
        			HashMap<String, Object> map;
        			ArrayList<HashMap<String, Object>> listItem;
        			
        		
        		listItem = new ArrayList<HashMap<String, Object>>();
  	        	maListViewPerso = (ListView)findViewById(R.id.listuserconnected);
  	        	
  	        	
  	        	if ( erreur == 1)
  	        	{
  	        		Toast.makeText(getApplicationContext(),"Pas d'amis" , Toast.LENGTH_LONG).show();  
  	        	}
  	        	
  	        	else
  	        	{
      	        	

      	        try {
      	        	
      	        	
      	        	JSONArray main = new JSONArray(response);
      	        	main.length();
      	        	
      	        	final JSONObject[] amis = new JSONObject[main.length()];
      	        	
      	        
      	        	

      	        	for    ( int i = 0 ; i< main.length() ; i++ )
      	        	{
      	        		
      	        		amis[i] = main.getJSONObject(i);
      	        		
      	        	    map = new HashMap<String, Object>();
      	        	    map.put("titre", amis[i].get("pseudo").toString());
      	                map.put("description", amis[i].get("email").toString());
      	                map.put("img", bmp[i])  ;
      	              map.put("id", amis[i].get("id").toString());
      	                listItem.add(map);	
      	        	} 	
		
         				
       	         SimpleAdapter mSchedule = new SimpleAdapter (getBaseContext(), listItem, R.layout.item,
	                     new String[] {"img", "titre", "description","id"}, new int[] {R.id.img, R.id.titre, R.id.description,R.id.id});
       	      mSchedule.setViewBinder(new MyViewBinder());
	              maListViewPerso.setAdapter(mSchedule);
      	        	
	              maListViewPerso.setOnItemClickListener(new OnItemClickListener() {

	      			
	      			 
	                
	                
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						
						final int IndexAmis = arg2;
						
						
						
						
						
						
						

						dialog = new Dialog(DashBoard.this);
		                dialog.setContentView(R.layout.dialoglist);

		                String pseudoo = null;
						try {
							pseudoo = amis[arg2].get("pseudo").toString();
							
						} catch (JSONException e) {

							e.printStackTrace();
						}
		                
		                dialog.setTitle(pseudoo);
		                dialog.setCancelable(true);
		                ImageView imgo = (ImageView) dialog.findViewById(R.id.ImageView01);
		                imgo.setImageBitmap(bmp[arg2]);             
		                Button retour = (Button) dialog.findViewById(R.id.Ret);
		                retour.setOnClickListener(new OnClickListener() {
		                public void onClick(View v) {
		                	dialog.cancel();

		                	
		                    }
		                });
		                
		                Button chat = (Button) dialog.findViewById(R.id.chat);
		                chat.setOnClickListener(new OnClickListener() {
		                public void onClick(View v) {
		                	dialog.cancel();
		                		   Message msg = Message.obtain(null, SimpleService.MSG_ADD_CHAT_ROOM);
		     	                msg.replyTo = mMessenger;
		     	                
		     	              /*
		     	               Bundle b = new Bundle();
		     	                try {
									b.putString("str1","chat%00%"+pseudo+"%"+amis[IndexAmis].get("pseudo").toString());
								} catch (JSONException e2){
									e2.printStackTrace();
								}
		     	                msg.setData(b);
		     	                try {
									mService.send(msg);
								} catch (RemoteException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
*/
		                	
		                	
		                	
		                	Intent nextScreen = new  Intent (getApplicationContext (), ChatBox.class );
		        			try {
								nextScreen.putExtra("id", amis[IndexAmis].get("id").toString());
								nextScreen.putExtra("pseudo", amis[IndexAmis].get("pseudo").toString());
								nextScreen.putExtra("pseudomoi", pseudo);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
		    				startActivity (nextScreen);
		                	
		                    }
		                }); 
		                
		                Button jouer = (Button) dialog.findViewById(R.id.jouer);
		                jouer.setOnClickListener(new OnClickListener() {
		                public void onClick(View v) {
		                	dialog.cancel();
		                	
		                	// envoyer msg par service de demande de jeu

		                	  Message msg = Message.obtain(null, SimpleService.MSG_ADD_CHAT_ROOM);
		     	                msg.replyTo = mMessenger;
		     	                
		     	               
		     	               Bundle b = new Bundle();
		     	                try {
									b.putString("str1","jeu%00%" +amis[IndexAmis].get("pseudo").toString());
								} catch (JSONException e2) {
									// TODO Auto-generated catch block
									e2.printStackTrace();
								}
		     	                msg.setData(b);
		     	                try {
									mService.send(msg);
								} catch (RemoteException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}

		                	
		                    }
		                });
		                
		                
		                
		             // img.setImageResource(R.drawable.ok);
		                dialog.show();
					}
	                ;
	      			
	      			
	      		
	               });
				} catch (Exception e) {
					
				}

        		
        		}
    		
        		
        			
        		}      			
        			
        }

        public class MyViewBinder implements ViewBinder {

        	
        	public boolean setViewValue(View view, Object data,String textRepresentation) {
        		if( (view instanceof ImageView) & (data instanceof Bitmap) ) 
        		{
        			ImageView iv = (ImageView) view;
        			Bitmap bm = (Bitmap) data;	
        			iv.setImageBitmap(bm);	
        			return true;
        		}
         
        		return false;
        	}	
        }
}   			
